package com.augurit.common.base.action;

import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.form.BaseForm;
import com.augurit.common.util.ExportExcel;
import com.augurit.common.util.JsonUtils;
import com.augurit.common.util.lang.CollectionUtils;

/**
 * 导出Excel的Action类
 */
@SuppressWarnings("serial")
public class ExportExcelAction extends ExtBaseAction{
	
	private String exportQueryParams;	//查询条件
	private String exportPropertyNames;	//要导出的属性列表，逗号分隔
	private String exportHeaderNames;	//要导出的列标题列表，逗号分隔

	/**
	 * 导出Excel
	 */
	protected String exportExcel(List resultSet) throws Exception {
		//获取输出流
		OutputStream out = this.getResponse().getOutputStream();
		
		//设置页面不缓存   
		this.getResponse().reset();   
		this.getResponse().setContentType("application/vnd.ms-excel");   
		this.getResponse().setHeader("Content-disposition", "attachment; filename=data.xls");     
		this.getResponse().setDateHeader("Expires", 0);
		
		//导出Execl
		ExportExcel.exportExcel(resultSet, this.getHeaderList(), this.getPropertyList(), out);
		return null;
	}
	
	/**
	 * 获取要导出的属性列表
	 */
	public List<String> getPropertyList(){
		if(this.exportPropertyNames != null && this.exportPropertyNames.trim().length() > 0){
			String[] propertyArray = this.exportPropertyNames.split(",");
			return CollectionUtils.toStringList(propertyArray);
		}
		return null;
	}
	
	public <T extends BaseForm> T getQueryParams(Class<T> formClass) throws Exception{
		return Struts2Utils.buildFromJson(this.exportQueryParams, formClass);
	}
	
	public Map<String, String> getQueryParams() throws Exception{
		return JsonUtils.convertToMap(this.exportQueryParams);
	}
	
	/**
	 * 获取要导出的列标题
	 */
	public List<String> getHeaderList(){
		if(this.exportHeaderNames != null && this.exportHeaderNames.trim().length() > 0){
			String[] headerArray  = this.exportHeaderNames.split(",");
			return CollectionUtils.toStringList(headerArray);
		}
		return null;
	}

	public String getExportPropertyNames() {
		return exportPropertyNames;
	}

	public void setExportPropertyNames(String exportPropertyNames) {
		this.exportPropertyNames = exportPropertyNames;
	}

	public String getExportHeaderNames() {
		return exportHeaderNames;
	}

	public void setExportHeaderNames(String exportHeaderNames) {
		this.exportHeaderNames = exportHeaderNames;
	}

	public String getExportQueryParams() {
		return exportQueryParams;
	}

	public void setExportQueryParams(String exportQueryParams) {
		this.exportQueryParams = exportQueryParams;
	}
}
